<template>
  <div class="form-single-fragment" style="position: relative;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini" label-position="right">
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="20">
          <el-col :span="12">
            <el-form-item label="专家姓名" prop="expertName">
              <el-input class="input-item" v-model="ruleForm.expertName" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属地区" prop="districtCode">
              <el-cascader v-model="areaCodes"
                           ref="ref_areaCodes"
                           :options="areaCodelist"
                           :props="areaCodeprops"
                           :show-all-levels="false"
                           clearable
                           @change="areaCodesChange"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="telephone">
              <el-input class="input-item" v-model="ruleForm.telephone" placeholder="请输入" maxlength="11" type='tel' onkeyup="value=value.replace(/[^\d]/g,'')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位属性" prop="unitAttribute">
              <el-input class="input-item" v-model="ruleForm.unitAttribute" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作单位" prop="enterpriseName">
              <el-input class="input-item" v-model="ruleForm.enterpriseName" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称" prop="qualification">
              <el-input class="input-item" v-model="ruleForm.qualification" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" prop="post">
              <el-input class="input-item" v-model="ruleForm.post" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专家费（元）">
              <el-input type="number" class="input-item" v-model="ruleForm.fee" placeholder="请输入"
                        maxlength="20"
                        oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+4)}if(value<0){value='0'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执业资格" prop="practiceQualification">
              <el-input class="input-item" v-model="ruleForm.practiceQualification" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <el-cascader class="input-item" v-model="ruleForm.deptId" :clearable="true"
                           placeholder="所属部门" :loading="loading"
                           :props="dropdownprops"
                           @visible-change="onDeptIdVisibleChange" :options="dropdownList"
                           @change="onDeptIdValueChange">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="industryType">
              <el-select v-model="ruleForm.industryType" placeholder="请选择">
                <el-option v-for="(item,index) in Industrylist" :key="index"
                           :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传附件" prop="fileId">
              <el-upload class="upload-demo"
                         :action="action"
                         :headers="headers"
                         :on-change="handleSuccess"
                         :on-remove="handleRemove"
                         :before-upload="beforeAvatarUpload"
                         :on-exceed="handleExceed"
                         :accept="acceptStr"
                         multiple
                         :limit="5"
                         :file-list="fileLists">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传word/pdf/ppt文件，且不超过500MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item style="padding: 20px 0;">
              <el-button size="mini" @click="onCancel(false)">取消</el-button>
              <el-button type="primary" size="mini" @click="submitForm()">保存</el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { SysDeptController } from '@/api';
import { ExpertKnowledge, EcologicalkKnowledge } from '@/api/knowledgeBases.js';
import { OnlineDictController } from '@/api/onlineController.js';
import { getToken } from '@/utils';
import { fileUploadFileDo } from '@/api/projectAdministration.js';
export default {
  name: 'Expertadd',
  props: {
    ExpertId: {
      default: undefined
    }
  },
  data () {
    return {
      item_title: '创建专家',
      action: fileUploadFileDo,
      fileLists: [],
      fileIndex: '',
      acceptStr: '.doc,.docx,.pdf,.ppt,.pptx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      isShowloading: false,
      loading: false,
      userId: null,
      Industrylist: [],
      dropdownList: [],
      dropdownprops: {
        label: 'deptName',
        value: 'deptId'
      },
      areaCodelist: [],
      areaCodes: [],
      areaCodeprops: {
        label: 'name',
        value: 'id',
        children: 'children',
        checkStrictly: true
      },
      ruleForm: {
        expertName: '',
        districtCode: '',
        telephone: '',
        unitAttribute: '',
        enterpriseName: '',
        qualification: '',
        post: '',
        fee: '',
        practiceQualification: '',
        deptId: '',
        industryType: '',
        fileId: ''
      },
      rules: {
        expertName: [{ required: true, message: '请输入', trigger: 'blur' }],
        districtCode: [{ required: true, message: '请选择', trigger: 'change' }],
        telephone: [{ required: true, message: '请输入', trigger: 'blur' }],
        unitAttribute: [{ required: true, message: '请输入', trigger: 'blur' }],
        enterpriseName: [{ required: true, message: '请输入', trigger: 'blur' }],
        qualification: [{ required: true, message: '请输入', trigger: 'blur' }],
        post: [{ required: true, message: '请输入', trigger: 'blur' }],
        practiceQualification: [{ required: true, message: '请输入', trigger: 'blur' }],
        deptId: [{ required: true, message: '请选择', trigger: 'change' }],
        industryType: [{ required: true, message: '请选择', trigger: 'blur' }]
      }
    };
  },
  computed: {
    isEdit () {
      return this.ExpertId != null && this.ExpertId !== '';
    },
    headers () {
      return {
        Authorization: getToken() || ''
      };
    }
  },
  mounted () {
    this.loadDeptmentDropdownList()
    this.loadareaCodelistDict()
    this.loadOnlineDictControllerData()
    if (this.isEdit) {
      this.loadknowledgedetail()
    }
  },
  created () {
  },
  methods: {
    /**
       * 知识库详情
       */
    loadknowledgedetail () {
      let params = this.ExpertId
      return new Promise((resolve, reject) => {
        ExpertKnowledge.detail(this, params).then(res => {
          this.ruleForm = res.data
          this.areaCodes.push(parseInt(res.data.districtCode))
          let fileIds = []
          let file = res.data.fileDoList
          if (file.length !== 0) {
            file.forEach((item) => {
              fileIds.push(item.fileId)
            })
            this.ruleForm.fileId = fileIds.join(',')
            this.fileLists = file.map(item => {
              return {
                name: item.fileName,
                response: {
                  data: {
                    filePath: item.filePath,
                    fileId: item.fileId
                  }
                }
              }
            })
          }
          this.$forceUpdate()
          this.$forceUpdate()
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
       * 行政区划
       */
    loadareaCodelistDict () {
      return new Promise((resolve, reject) => {
        EcologicalkKnowledge.listDict(this).then(res => {
          let areaCodelist = res.data
          let areaCodelistnew = []
          areaCodelist.forEach((item, index) => {
            if (!item.parentId) {
              item.children = []
              areaCodelistnew.push(item)
            }
          })
          areaCodelistnew.forEach((item1, index1) => {
            let info = areaCodelist.find((item2, index2) => {
              return item1.id === item2.parentId
            })
            if (info) {
              item1.children = []
              areaCodelist.forEach((item3, index3) => {
                if (item1.id === item3.parentId) {
                  item1.children.push(item3)
                }
              })
            } else {
              item1.children = null
            }
          })
          areaCodelistnew.forEach((item4, index4) => {
            if (item4.children) {
              item4.children.forEach((item5, index5) => {
                let info2 = areaCodelist.find((item6, index6) => {
                  return item5.id === item6.parentId
                })
                if (info2) {
                  item5.children = []
                  areaCodelist.forEach((item7, index7) => {
                    if (item5.id === item7.parentId) {
                      item5.children.push(item7)
                    }
                  })
                } else {
                  item5.children = null
                }
              })
            }
          })
          this.areaCodelist = areaCodelistnew
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
       * 选择行政区划
       */
    areaCodesChange () {
      let info = this.areaCodes
      let length = info.length - 1
      this.ruleForm.districtCode = info[length]
      this.$refs['ref_areaCodes'].dropDownVisible = false
    },
    /**
       * 所属部门下拉数据获取函数
       */
    loadDeptmentDropdownList () {
      return new Promise((resolve, reject) => {
        let params = {};
        SysDeptController.list(this, params).then(res => {
          this.dropdownList = res.data.dataList;
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
       * 所属部门下拉框显隐
       */
    onDeptIdVisibleChange (show) {

    },
    /**
       * 所属部门选中值改变
       */
    onDeptIdValueChange (value) {
      this.ruleForm.deptId = Array.isArray(value) ? value[value.length - 1] : undefined;
      this.loadDeptPost();
    },
    /**
       * 所属行业
       */
    loadOnlineDictControllerData () {
      let params = {
        dictId: '1475422753933758464'
      }
      return new Promise((resolve, reject) => {
        OnlineDictController.view(this, params).then(res => {
          this.Industrylist = JSON.parse(res.data.dictDataJson).dictData
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
       * 上传文件-成功
       */
    handleSuccess (file, fileList) {
      fileList.forEach((item, index) => {
        if (item.response && item.response.success === false) {
          this.$message({
            showClose: true,
            message: '第' + Number(index + 1) + '调数据上传失败，原因：' + item.response.errorMessage,
            type: 'error'
          });
          fileList.splice(index, 1)
        }
      })
      this.fileLists = fileList
    },
    /**
       * 上传文件-删除
       */
    handleRemove (file, fileList) {
      this.fileLists = fileList
    },
    /**
       * 上传图片限制条件
       */
    beforeAvatarUpload (file, fileList) {
      // const isJPG = file.type === 'image/jpeg'
      // const isLt500M = file.size / 1024 < 500
      // if (!isJPG) {
      //   this.$message.error('上传文件格式不对!')
      //   return false
      // }
      // if (!isLt500M) {
      //   this.$message.error('上传文件大小不能超过 500M!')
      //   return false
      // }
      // return isJPG && isLt500M
    },
    /**
       * 上传图片条数限制
       */
    handleExceed (files, fileList) {
      this.$message.warning(`最大文件上传数 5 个文件，本次上传数 ${files.length + fileList.length} 个文件，已超出限制。`);
    },
    /**
       * 提交表单
       */
    submitForm () {
      if (this.fileLists.length !== 0) {
        if (this.fileLists.length > 5) {
          this.$message({
            showClose: true,
            message: '最多上传5个附件！',
            type: 'warning'
          });
          return false
        }
        let filesnew = []
        this.fileLists.forEach((item) => {
          filesnew.push(item.response.data.fileId)
        })
        this.ruleForm.fileId = filesnew.join(',')
      }
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          let params = this.ruleForm;
          if (this.ExpertId) { // 修改
            return new Promise((resolve, reject) => {
              ExpertKnowledge.update(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '修改成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          } else { // 添加
            return new Promise((resolve, reject) => {
              ExpertKnowledge.add(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '添加成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onCancel (isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    }
  }
}
</script>

<style scoped>
  h3{border-bottom: 1px solid #E9E9EB;padding: 0 0 10px;}
  .table_container{margin: 10px 0;}
  .form-single-info{display: flex;justify-content: center;}
  .el-form-info{box-shadow: 0 0 10px rgba(0,0,0,0.05);padding: 20px;}
  .el-form-info strong{margin: 0 10px;}
  .el-form-info .el-time-picker{width: 100%;}
</style>
